package com.h2.ref.server.web.user;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.h2.ref.server.user.IUserService;
import com.h2.ref.server.web.ViewConstants;

@Controller
public class UserRegistration {
   
   private IUserService _userService;
   
   ////
   ////
   
   @InitBinder
   protected void initBinder(WebDataBinder binder) {
      if(binder.getTarget() instanceof UserFormData) {
         binder.setValidator(new UserValidator());
      }
   }
   
   @RequestMapping(value = ViewConstants.REGISTER_USER,
         method = RequestMethod.GET)
   public String setupForm(Model model) {
      UserFormData user = new UserFormData();
      model.addAttribute("user", user);
      return ViewConstants.REGISTER_USER_VIEW;
   }
   
   @RequestMapping(value = ViewConstants.REGISTER_USER,
         method = RequestMethod.POST)
   public String processSubmit(Model model,
            @ModelAttribute("user")
            UserFormData user, BindingResult result) {
      
      if (result.hasErrors()) {
         return ViewConstants.REGISTER_USER_VIEW;
      }
      else if(getUserService().findByUserName(user.getName()) != null) {
         result.rejectValue("name", "register.user.invalid");
         return ViewConstants.REGISTER_USER_VIEW;
      }
      else if(getUserService().findByEmail(
            user.getUserDetails().getEmail()) != null) {
         result.rejectValue("userDetails.email",
               "register.email.invalid.duplicate");
         return ViewConstants.REGISTER_USER_VIEW;
      }
      
      //add user
      getUserService().addRegisteredUser(user.copy(), true);
      
      return ViewConstants.REDIRECT + ViewConstants.SIGNIN;
   }

   /**
    * @return the userService
    */
   public IUserService getUserService() {
      return _userService;
   }

   /**
    * @param userService the userService to set
    */
   public void setUserService(IUserService userService) {
      _userService = userService;
   }

}
